//校园通相关接口
import HTTPREQUEST from "./http"
import Taro from "@tarojs/taro";

//校园通默认根路径
export const BASE_CAMPUS_URL = "https://campus.lancooedu.com"

export const get = (url, data?, header?, loading?) => HTTPREQUEST.get(`${BASE_CAMPUS_URL}${url}`, data, header, loading)
export const post = (url, data?, header?, loading?) => HTTPREQUEST.post(`${BASE_CAMPUS_URL}${url}`, data, header, loading)
export const put = (url, data?, header?, loading?) => HTTPREQUEST.put(`${BASE_CAMPUS_URL}${url}`, data, header, loading)
export const del = (url, data?, header?, loading?) => HTTPREQUEST.delete(`${BASE_CAMPUS_URL}${url}`, data, header, loading)

type ResultType<T> = { error: number, msg: string, data: T };

//统一处理http&业务response
async function responseHandler<T>(response: Promise<ResultType<T>>, showToast: boolean = false): Promise<T> {
   //HTTP请求层response统一处理
   let res: ResultType<T> | null = null
   try {
      res = await response;
   } catch (err) {
      //默认无异常弹窗提示
      if (showToast) {
         await Taro.showToast({icon: 'none', title: "网络错误"})
      }
      throw new Error("网络错误")//与业务（接口）层统一catch处理异常
   }

   //业务（接口）层result返回统一处理
   if (res.error === 0 || res.error === 1) {
      return res.data
   }
   let message = res.msg || "服务器异常";
   if (showToast) {
      await Taro.showToast({icon: 'none', title: message})
   }
   throw new Error(message)//与http层统一catch处理异常
}

//获取公众号assessToken
interface TicketData{
  ticket:string//
  expires_in:number//有效时长
  errcode:string
  errmsg:string
}
export const getTicket = (schoolId:string) => responseHandler<TicketData>(get(`/wxapi/getJsapiTicket`, { schoolId:schoolId}));
